package com.koron.system.common.util;

import com.banboocloud.Codec.BamboocloudFacade;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public abstract class BamboocloudUtils {

    public static void checkUsernamePassword(String username, String password) {
        log.info("username --->" + username + "  password --- >" + password + " ----ok");
    }

    public static String getPlaintext(String ciphertext, String key, String type) {
        return BamboocloudFacade.decrypt(ciphertext, key, type);
    }

    public static Boolean verify(Map<String, Object> reqmap, String type) {
        Map<String, Object> verifymap = new TreeMap<>();
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = reqmap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            verifymap.put(key, reqmap.get(key));
        }
        Iterator<String> ittree = verifymap.keySet().iterator();
        while (ittree.hasNext()) {
            String key = ittree.next();
            if (!"signature".equals(key)) {
                sb.append(key).append("=").append(verifymap.get(key)).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        log.info(reqmap.get("signature") + "  now  " + sb);
        return BamboocloudFacade.verify(reqmap.get("signature").toString(), sb.toString(), type);
    }

    public static String getRequestBody(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String str = "";
        try {
            br = request.getReader();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            log.info(e.getMessage());
            if (br != null)
                try {
                    br.close();
                } catch (IOException eo) {
                    log.error(eo.getMessage(),eo);
                }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }
            }
        }
        return sb.toString();
    }
}
